import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/user';

const httpInstance = axios.create({
  baseURL: import.meta.env.VITE_API_URL || 'http://localhost:8080/api',
  timeout: 5000,
  withCredentials: true, // 关键：启用Cookie传递
});

// 请求拦截器
httpInstance.interceptors.request.use(config => {
  const userStore = useUserStore();
  
  // 开发环境强制模拟Session
  if (import.meta.env.MODE === 'development') {
    config.headers['X-Mock-Session'] = 'active'; // 可选：告诉后端这是模拟请求
    if (!document.cookie.includes('SESSION_ID')) {
      document.cookie = `SESSION_ID=mock-session-id; Path=/; Max-Age=86400`;
    }
  }

  return config;
}, error => {
  return Promise.reject(error);
});

// 响应拦截器
httpInstance.interceptors.response.use(response => {
  return response.data;
}, error => {
  if (error.response?.status === 401) {
    const userStore = useUserStore();
    userStore.resetUserState(); // 清空前端登录状态
    window.location.href = '/login'; // 跳转到登录页
  }
  
  ElMessage({
    type: 'error',
    message: error.response?.data?.message || '请求失败',
  });
  return Promise.reject(error);
});

export default httpInstance;